package com.xuan.api.sms.service.impl;


import com.xuan.api.sms.service.SmsService;
import com.xuan.constant.MQConstant;
import com.xuan.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {


    @Value("${sms.appcode}")
    private String appcode;

    @Value("${sms.tplId}")
    private String tplId;

    /**
     * 监听发送消息
     * @param map
     */
    @Override
    @RabbitListener(queuesToDeclare = @Queue(MQConstant.SEND_SMS_QUEUE_NAME))
    public void sendSms(@Payload Map<String, Object> map) {

        String code = (String) map.get("code");

        String mobile = (String) map.get("mobile");

        log.info("手机号为"+mobile+";;;验证码为"+code);

        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        //appcode = "0984ea8846284961b1f723fcc75035c1";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("param", "code:"+code);
        querys.put("tpl_id",tplId);
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            if (response.getStatusLine().getStatusCode() == 200){
                log.info("发送成功");
            }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发送失败");
        }


    }
}
